package com.example.myblog.controller;



import com.example.myblog.service.BlogService;
import com.example.myblog.service.TagService;
import com.example.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * Created by asus on 2020/5/26 13:36
 */
@Controller
public class IndexControler {

    @Autowired
    private BlogService blogService;

    @Autowired private TypeService typeService;

    @Autowired private TagService tagService;

    @GetMapping("/")
    public String index(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable
                        , Model model){
        model.addAttribute("page",blogService.ListBlog(pageable));
        model.addAttribute("types",typeService.ListTypeTop(6));
        model.addAttribute("tags",tagService.ListTagTop(10));
        model.addAttribute("recommendBlogs",blogService.ListRecommendBlogTop(8));
        return "index";
    }

    //把博客详情的内容展示
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }

    //前台查询
    @PostMapping("/search")
    public String search(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable
                        ,@RequestParam String query, Model model){
        model.addAttribute("page",blogService.ListBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "search";
    }
    //页脚的推荐
    @GetMapping("/footer/newblog")
    public String newblogs(Model model){
        model.addAttribute("newblogs",blogService.ListRecommendBlogTop(3));
        return "_fragments :: newblogList";
    }
    @GetMapping("/admin/footer/newblog")
    public String adminnewblogs(Model model){
        model.addAttribute("newblogs",blogService.ListRecommendBlogTop(3));
        return "admin/_fragments :: newblogList";
    }
}
